package com.xgq.drink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgq.drink.entity.DiscountClaim;
import com.xgq.drink.entity.DiscountInfo;
import com.xgq.drink.entity.Product;
import com.xgq.drink.entity.R;
import com.xgq.drink.mapper.DiscountClaimMapper;
import com.xgq.drink.mapper.DiscountInfoMapper;
import com.xgq.drink.service.IDiscountInfoService;
import com.xgq.drink.service.IProductService;
import com.xgq.drink.utils.RUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 优惠信息表 服务实现类
 * </p>
 *
 * @author xgq
 * @since 2025-03-04
 */
@Service
public class DiscountInfoServiceImpl extends ServiceImpl<DiscountInfoMapper, DiscountInfo> implements IDiscountInfoService {
    @Autowired
    private DiscountInfoMapper discountInfoMapper;

    @Autowired
    private DiscountClaimMapper discountClaimMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R createDiscountInfo(DiscountInfo discountInfo) {
        if (discountInfo == null || discountInfo.getDiscountName() == null || discountInfo.getDiscountName().isEmpty()) {
            return RUtils.fail("优惠券名称不能为空");
        }
        discountInfo.setStatus(1);  // 1-上架状态
        discountInfo.setCreatedAt(LocalDateTime.now());
        discountInfo.setUpdatedAt(LocalDateTime.now());
        boolean saved = save(discountInfo);
        return saved ? RUtils.success("优惠券创建成功", discountInfo) : RUtils.fail("优惠券创建失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateDiscountInfo(DiscountInfo discountInfo) {
        DiscountInfo existingDiscount = getById(discountInfo.getDiscountId());
        if (existingDiscount == null) {
            return RUtils.fail("优惠券不存在");
        }
        discountInfo.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = updateById(discountInfo);
        return updated ? RUtils.success("优惠券更新成功", discountInfo) : RUtils.fail("优惠券更新失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deactivateDiscountInfo(Long discountId) {
        if (discountId == null) {
            return RUtils.fail("优惠券ID不能为空");
        }
        
        DiscountInfo discount = getById(discountId);
        if (discount == null) {
            return RUtils.fail("优惠券不存在");
        }
        
        discount.setStatus(0);  // 0-下架状态
        discount.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = updateById(discount);
        return updated ? RUtils.success("优惠券下架成功") : RUtils.fail("优惠券下架失败");
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deactivateDiscountInfo2(Long discountId) {
        if (discountId == null) {
            return RUtils.fail("优惠券ID不能为空");
        }

        DiscountInfo discount = getById(discountId);
        if (discount == null) {
            return RUtils.fail("优惠券不存在");
        }

        discount.setStatus(1);  // 0-下架状态
        discount.setUpdatedAt(LocalDateTime.now());

        boolean updated = updateById(discount);
        return updated ? RUtils.success("优惠券下架成功") : RUtils.fail("优惠券下架失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R replenishDiscountInfo(Long discountId, Integer maxUserClaims) {
        if (discountId == null || maxUserClaims == null || maxUserClaims <= 0) {
            return RUtils.fail("参数错误");
        }
        
        DiscountInfo discount = getById(discountId);
        if (discount == null) {
            return RUtils.fail("优惠券不存在");
        }
        
        discount.setDiscountNum(discount.getMaxUserClaims() + maxUserClaims);
        discount.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = updateById(discount);
        return updated ? RUtils.success("优惠券补货成功") : RUtils.fail("优惠券补货失败");
    }

    @Override
    public R getDiscountInfos(String discountType, Long shopId, Long productId, Integer page, Integer size) {
        Page<DiscountInfo> pageParam = new Page<>(page, size);
        QueryWrapper<DiscountInfo> queryWrapper = new QueryWrapper<>();
        System.out.println("查询优惠券");
        System.out.println(shopId);
        if (discountType != null && !discountType.isEmpty()) {
            queryWrapper.eq("discount_type", discountType);
        }
        if (shopId != null) {
            System.out.println("查询优惠券111");
            queryWrapper.eq("shop_id", shopId);
        }
        if (productId != null) {
            queryWrapper.eq("product_id", productId);
        }
        
//        queryWrapper.eq("status", 1);  // 只查询上架的优惠券
        queryWrapper.orderByDesc("created_at");
        
        Page<DiscountInfo> result = page(pageParam, queryWrapper);
        return RUtils.success("查询成功", result);
    }

    @Override
    public R getDiscountInfo(Long discountId) {
        if (discountId == null) {
            return RUtils.fail("优惠券ID不能为空");
        }
        
        DiscountInfo discount = getById(discountId);
        return discount != null ? RUtils.success("查询成功", discount) : RUtils.fail("优惠券不存在");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R claimDiscountInfo(Long discountId) {
        if (discountId == null) {
            return RUtils.fail("优惠券ID不能为空");
        }
        
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return RUtils.fail("用户未登录");
        }
        Long userId = Long.parseLong(authentication.getName());
        
        // 检查优惠券是否存在且有效
        DiscountInfo discount = getById(discountId);
        if (discount == null || discount.getStatus() != 1) {
            return RUtils.fail("优惠券不存在或已下架");
        }
        
        // 检查用户领取次数
        QueryWrapper<DiscountClaim> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("discount_id", discountId);
        DiscountClaim existingClaim = discountClaimMapper.selectOne(queryWrapper);
        
        if (existingClaim != null) {
            if (existingClaim.getClaimCount() >= discount.getMaxUserClaims()) {
                return RUtils.fail("已达到最大领取次数");
            }
            existingClaim.setClaimCount(existingClaim.getClaimCount() + 1);
            existingClaim.setClaimedAt(LocalDateTime.now());
            discountClaimMapper.updateById(existingClaim);
        } else {
            DiscountClaim newClaim = new DiscountClaim();
            newClaim.setUserId(userId);
            newClaim.setDiscountId(discountId);
            newClaim.setClaimCount(1);
            newClaim.setClaimedAt(LocalDateTime.now());
            newClaim.setStatus(1);  // 1-有效状态
            discountClaimMapper.insert(newClaim);
        }
        
        return RUtils.success("领取成功");
    }
    @Autowired
    private IProductService productService;
    @Override
    public DiscountInfo getDiscountInfoById(Long discountId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("discount_id", discountId);
        return discountInfoMapper.selectOne(queryWrapper);
    }
    public List<DiscountInfo> getDiscountsByProductId(Long productId) {
        // 1. 验证商品存在
        Product product = productService.getById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        // 2. 构建查询条件
        QueryWrapper<DiscountInfo> wrapper = new QueryWrapper<>();

        // 商品专属优惠券（PRODUCT类型）
        wrapper.eq("product_id", productId)
                .eq("discount_type", "PRODUCT")
                .eq("status", 1) // 假设1表示启用状态
                .le("start_date", LocalDate.now())
                .ge("end_date", LocalDate.now());

        // 商家优惠券（SHOP类型）
        wrapper.or(qw -> qw.eq("discount_type", "SHOP")
                .eq("shop_id", product.getBrandId()) // 假设商品表有brand_id字段
                .eq("status", 1)
                .le("start_date", LocalDate.now())
                .ge("end_date", LocalDate.now()));

        // 平台优惠券（OFFICIAL类型）
        wrapper.or(qw -> qw.eq("discount_type", "OFFICIAL")
                .eq("status", 1)
                .le("start_date", LocalDate.now())
                .ge("end_date", LocalDate.now()));

        return list(wrapper);
    }
}
